<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElForm, ElButton, ElTable, ElTableColumn, ElInput, ElMessage } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { getBacthUpdateTableListApi } from '@/api/operator'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import Operator from './Operator.vue'

interface Props {
  currentRow?: any
}

const props = defineProps<Props>()

const { t } = useI18n()

// 表单数据
const formData = reactive({
  group: [] as (string | number)[], // 分组（数组类型，支持多选）
  operator: [] as (string | number)[] // 操作员（数组类型，支持多选）
})
const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const saveLoading = ref(false)
// 列表数据
const tableData = ref<Array<{ id: number; uid: number; oprName: string; income: number; score: number; oprid: number }>>([])
// 选中的表格行
const selectedTableRows = ref<Array<{ id: number; uid: number; oprName: string; income: number; score: number; oprid: number }>>([])

// 表格数据
const getBacthUpdateTableList = async (grpids: number[] = []) => {
  try {
    const res = await getBacthUpdateTableListApi({
      id: props.currentRow?.id,
      grpid: grpids.length > 0 ? Number(grpids[0]) : undefined
    })
    if (res && res.data) {
      tableData.value = res.data.items.map((item: any) => ({
        id: item.id,
        uid: item.uid || item.id, // 优先使用uid，如果没有则使用id
        oprName: item.oprName,
        income: item.income || 0, // 使用API返回的income值，默认为0
        score: item.score,
        oprid: item.oprid // 添加操作员ID
      }))
    }
  } catch (error) {
    console.error('获取操作员列表失败:', error)
  }
}

const BacthUpdateRef = ref<any>()

const AddAction = () => {
  dialogTitle.value = '添加账号'
  dialogVisible.value = true
  actionType.value = 'operator'
}
const add = async () => {
  if (!BacthUpdateRef.value || typeof BacthUpdateRef.value.getSelected !== 'function') return
  const selected = BacthUpdateRef.value.getSelected() as Array<{ uid: string | number; oprName: string; score: number; income?: number }>
  if (!selected || selected.length === 0) {
    ElMessage.warning('请选择要添加的账号')
    return
  }
  const existingUidSet = new Set(tableData.value.map((r) => String(r.uid)))
  const toAdd = selected.filter((row) => !existingUidSet.has(String(row.uid)))
  if (toAdd.length === 0) {
    ElMessage.info('所选账号已全部在列表中')
    dialogVisible.value = false
    return
  }
  tableData.value = tableData.value.concat(
    toAdd.map((row: any) => ({
      // 优先使用隐藏的 id，其次回退到 uid
      id: Number(row.id ?? row.uid),
      uid: Number(row.uid),
      oprName: row.oprName,
      income: 0,
      score: row.score,
      oprid: 0
    }))
  )
  ElMessage.success(`成功添加 ${toAdd.length} 个账号`)
  dialogVisible.value = false
}

// 删除选中行的操作员
const removeAllOperators = () => {
  if (selectedTableRows.value.length === 0) {
    ElMessage.warning('请选择要删除的项')
    return
  }
  
  // 获取选中行的ID集合
  const selectedIds = new Set(selectedTableRows.value.map(row => row.id))
  
  // 从表格数据中移除选中的行
  tableData.value = tableData.value.filter(row => !selectedIds.has(row.id))
  
  // 清空选中状态
  selectedTableRows.value = []
  
  ElMessage.success(`成功删除 ${selectedIds.size} 个操作员`)
}

const handleIncomeChange = (value: string | number, row: any) => {
  const num = typeof value === 'number' ? value : Number(value)
  row.income = Number.isNaN(num) ? 0 : num
}

const formRef = ref<InstanceType<typeof ElForm>>()
const tableRef = ref<InstanceType<typeof ElTable>>()

// 表格选择变化处理
const handleSelectionChange = (selection: Array<{ id: number; uid: number; oprName: string; income: number; score: number; oprid: number }>) => {
  selectedTableRows.value = selection
}

const submit = async () => {
  // 如果未手动勾选，则默认提交表格中的全部行
  const sourceRows = selectedTableRows.value.length > 0 ? selectedTableRows.value : tableData.value
  
  // 验证收益值必须大于0
  const invalidRows = sourceRows.filter((item) => {
    const income = Number(item.income)
    return Number.isNaN(income) || income <= 0
  })
  
  if (invalidRows.length > 0) {
    ElMessage.warning('收益值必须大于0，请检查并修正后再提交')
    return null
  }
  
  const result = {
    id: props.currentRow.id,
    score: sourceRows.reduce((total, item) => total + parseFloat(String(item.score || 0)), 0),
    remarks: '批量更新操作',
    incs: sourceRows.map((item) => ({
      id: item.id,
      income: Number.isNaN(Number(item.income)) ? 0 : Number(item.income)
    }))
  }
  return result
}

// 组件挂载时获取分组数据
onMounted(() => {
  getBacthUpdateTableList()
})

defineExpose({
  submit
})
</script>

<template>
  <div class="batch-update-container">
    <ElForm ref="formRef" :model="formData" class="batch-form">
      <!-- 第二排：操作员表格 -->
      <div class="table-container">
        <!-- 表格内部的操作员选择和按钮 -->
        <div class="table-header-controls">
          <div class="operator-buttons">
            <ElButton type="primary" @click="AddAction">添加</ElButton>
            <ElButton type="danger" @click="removeAllOperators">删除</ElButton>
          </div>
        </div>
        
        <!-- 表格 -->
        <ElTable ref="tableRef" :data="tableData" border style="width: 100%" row-key="id" @selection-change="handleSelectionChange">
          <ElTableColumn type="selection" width="55" align="center" />
          <ElTableColumn prop="uid" label="UID" align="center" />
          <ElTableColumn prop="oprName" label="操手名称" align="center" />
          <ElTableColumn prop="income" label="收益" align="center" >
          <template #default="{ row }">
              <ElInput 
                v-model="row.income" 
                @change="(val) => handleIncomeChange(val, row)"
                size="small"
                placeholder="请输入收益"
              />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="score" label="当前总积分" align="center" />
        </ElTable>
      </div>
    </ElForm>
  </div>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :maxHeight="400">
    <Operator
      v-if="actionType === 'operator'"
      ref="BacthUpdateRef"
      :preselected-uids="tableData.map((r) => r.uid)"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="add"
      >
        {{ t('exampleDemo.add') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style scoped>
.batch-update-container {
  padding: 16px 20px;
}

.batch-form {
  width: 100%;
}

/* 第一排：分组 */
.group-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 0;
}

.group-label {
  width: 80px;
  text-align: left;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  line-height: 32px;
  padding-left: 40px;
  padding-right: 12px;
  flex-shrink: 0;
}

/* 第二排：表格容器 */
.table-container {
  margin-top: -10px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

/* 表格内部的操作员选择和按钮 */
.table-header-controls {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.operator-select {
  flex: 0 0 auto;
  margin-right: 20px;
}

.operator-buttons {
  display: flex;
  gap: 16px;
  align-items: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #303133;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
  min-height: 28px;
}

:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-select) {
  border-radius: 4px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .table-header-controls {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .operator-select {
    width: 100%;
  }
  
  .operator-select .el-select {
    width: 100% !important;
  }
  
  .operator-buttons {
    justify-content: center;
  }
}
</style>